﻿using DataBaseConnect.App.UserApp;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using System.Collections.Generic;
using Utils;
using DataBaseConnect.App.RoleApp;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace CoreMVC.Jurisdiction.Manage.Controllers
{
    public class LoginController : Controller
    {
        public IUserAppService _userAppService;
        public IRoleAppService _roleAppService;
        public LoginController(IUserAppService userAppService, IRoleAppService roleAppService)
        {
            _userAppService = userAppService;
            _roleAppService = roleAppService;
        }

        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Login()
        {
            return View();
        }

        /// <summary>
        ///  登录验证
        /// </summary>  
        /// <param name="Name">登录姓名</param>
        /// <param name="Password">登录密码</param>
        /// <param name="ReturnUrl">登录前访问地址</param>
        /// <returns>陈杰 by 2017-09-15</returns>
        // GET: /<controller>/
        public async Task<IActionResult> LoginAsync(string Name, string Password, string ReturnUrl)
        {
            OperateStatus operateStatus = new OperateStatus();
            if (ModelState.IsValid)
            {
                //登陆授权
                var claims = new List<Claim>();
                var user = _userAppService.GetUser(Name, Password);
                if (user != null)
                {
                    var roleId = _roleAppService.GetUserRole(user.UserId);
                    // 保存要记录的值(cookie)
                    claims.Add(new Claim(ClaimTypes.Name, Name));  // 用户名
                    var indentity = new ClaimsIdentity(claims, "cookie");
                    indentity.AddClaim(new Claim("Password", Password)); // 密码
                    indentity.AddClaim(new Claim(ClaimTypes.Sid, user.UserId.ToString())); // 用户id
                    indentity.AddClaim(new Claim("RoleUserId", roleId == null ? 0.ToString() : roleId.RoleId.ToString())); // 登录用户角色id
                    var principal = new ClaimsPrincipal(indentity);
                    await HttpContext.SignInAsync(
                        CookieAuthenticationDefaults.AuthenticationScheme,
                        principal);

                    //验证是否授权成功
                    if (principal.Identity.IsAuthenticated)
                    {
                        operateStatus.Message = "登录成功";
                        operateStatus.ResultSign = ResultSign.Successful;
                        //  return RedirectToAction("Index");
                    }
                }
                else
                {
                    operateStatus.Message = "登录失败";
                    operateStatus.ResultSign = ResultSign.Error;
                }
            }
            return Json(operateStatus);
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Logout(string ReturnUrl)
        {
            // 用户用户信息
            //var userId = User.FindFirst(ClaimTypes.Sid).Value;
            //var userName = User.Identity.Name;

            //获取用户名方法2  
            //string username2 = User.FindFirst(ClaimTypes.Name).Value;
            //获取名字叫password的值  
            // string password = User.FindFirst("Password").Value;


            OperateStatus operateStatus = new OperateStatus();
            if (HttpContext.User.Identity.IsAuthenticated)
            {
                try
                {
                    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                    operateStatus.Message = "退出成功";
                    operateStatus.ResultSign = ResultSign.Successful;
                }
                catch (System.Exception e)
                {
                    operateStatus.Message = "退出失败" + e.Message;
                    operateStatus.ResultSign = ResultSign.Error;
                }
            }
            return Json(operateStatus);
        }
    }
}
